package it.bradipao.deschartsdemo.slice;

import it.bradipao.deschartsdemo.ResourceTable;
import it.bradipao.deschartsdemo.fraction.BarChartFraction;
import it.bradipao.deschartsdemo.fraction.LineChartFraction;
import it.bradipao.deschartsdemo.fraction.StackedBarChartFraction;
import it.bradipao.deschartsdemo.fraction.StackedLineChartFraction;
import it.bradipao.deschartsdemo.fraction.StyledXyChartFraction;
import it.bradipao.deschartsdemo.fraction.XyChartFraction;
import it.bradipao.deschartsdemo.spinner.MaterialSpinner;

import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.ability.fraction.FractionAbility;
import ohos.aafwk.content.Intent;
import ohos.agp.components.AttrHelper;
import ohos.agp.components.Component;
import ohos.agp.components.DependentLayout;
import ohos.agp.components.LayoutScatter;
import ohos.agp.utils.Color;
import ohos.agp.utils.LayoutAlignment;
import ohos.agp.window.dialog.BaseDialog;
import ohos.agp.window.dialog.CommonDialog;
import ohos.agp.window.dialog.PopupDialog;
import ohos.agp.window.dialog.ToastDialog;
import ohos.agp.window.service.WindowManager;
import ohos.global.configuration.Configuration;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;
import ohos.multimodalinput.event.TouchEvent;
import ohos.vibrator.agent.VibratorAgent;
import ohos.vibrator.bean.VibrationPattern;

import java.util.List;

/**
 * MainAbilitySlice
 *
 * @since 2021-07-30
 */
public class MainAbilitySlice extends AbilitySlice {
    private static final HiLogLabel LABEL = new HiLogLabel(HiLog.LOG_APP, 0x00201, "MainAbilitySlice");
    private boolean isLongClick;
    private boolean isShowMore;
    private long id_menus_onClick_time;
    private VibratorAgent vibratorAgent;
    private Integer vibratorId;
    private DependentLayout dependLayout;
    private ToastDialog toastDialog;

    private static final String[] OHOS_VERSIONS = {
        "XY chart",
        "STYLED XY chart",
        "LINE chart",
        "STACKED LINE chart",
        "BAR chart",
        "STACKED BAR chart"
    };

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ac_main);
        WindowManager.getInstance().getTopWindow().get().setNavigationBarColor(Color.WHITE.getValue());
        initView();
        initVibrator();
    }

    /**
     * Save currentIndex
     *
     * @since 2021-07-30
     */
    public static class Save {
        /**
         * currentIndex
         */
        public static int currentIndex = 0;
    }

    private void initView() {
        dependLayout = (DependentLayout) findComponentById(ResourceTable.Id_dependLayout);
        MaterialSpinner spinner = (MaterialSpinner) findComponentById(ResourceTable.Id_spinner);
        spinner.setItems(OHOS_VERSIONS);
        spinner.setTextSize(50);
        spinner.setHintColor(new Color(Color.getIntColor("#E7E7E7")));
        spinner.setArrowColor(Color.getIntColor("#878787"));
        layoutShow(Save.currentIndex);
        spinner.setSelectedIndex(Save.currentIndex);
        Configuration configuration = MainAbilitySlice.this.getApplicationContext().getResourceManager().getConfiguration();
        if (configuration.direction == Configuration.DIRECTION_HORIZONTAL) {
            findComponentById(ResourceTable.Id_dl_sort).setMarginRight(AttrHelper.vp2px(400, this));
        }
        spinner.setOnItemSelectedListener(new MaterialSpinner.OnItemSelectedListener<String>() {
            @Override
            public void onItemSelected(MaterialSpinner view, int position, long id, String item) {
                view.setHintColor(new Color(Color.getIntColor("#E7E7E7")));
                if (Save.currentIndex == position) {
                    return;
                }
                layoutShow(position);
                Save.currentIndex = position;
            }
        });

        findComponentById(ResourceTable.Id_image_right).setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                HiLog.info(LABEL, "onCLick 98");
                if (System.currentTimeMillis() - id_menus_onClick_time < 200) {
                    return;
                }
                id_menus_onClick_time = System.currentTimeMillis();
                if (!isShowMore) {
                    destroyDialog(toastDialog);
                    PopupDialog popupDialog = new PopupDialog(MainAbilitySlice.this, dependLayout);
                    popupDialog.setHasArrow(false);
                    popupDialog.setAutoClosable(true);
                    popupDialog.setAlignment(LayoutAlignment.RIGHT | LayoutAlignment.TOP);
                    Component component1 = LayoutScatter.getInstance(MainAbilitySlice.this).parse(ResourceTable.Layout_xui_popup_layout, null, true);
                    popupDialog.setCustomComponent(component1);
                    popupDialog.show();
                }
                isShowMore = false;
                isLongClick = false;
            }
        });

        findComponentById(ResourceTable.Id_image_right).setTouchEventListener(new Component.TouchEventListener() {

            @Override
            public boolean onTouchEvent(Component component, TouchEvent touchEvent) {
                int action = touchEvent.getAction();
                if (action == TouchEvent.PRIMARY_POINT_DOWN) {
                    isLongClick = true;
                    getUITaskDispatcher().delayDispatch(new Runnable() {
                        @Override
                        public void run() {
                            if (isLongClick) {
                                showMoreToastDialog();
                                isShowMore = true;
                            }
                        }
                    }, 1000);
                } else if (action == TouchEvent.PRIMARY_POINT_UP) {
                    isShowMore = false;
                    isLongClick = false;
                }
                return false;
            }
        });
    }

    private void showMoreToastDialog() {
        if (hasVibrator()) {
            startVibrator();
        }
        toastDialog = new ToastDialog(MainAbilitySlice.this);
        Component component1 = LayoutScatter.getInstance(MainAbilitySlice.this).parse(ResourceTable.Layout_xui_toast_layout, null, true);
        toastDialog.setAlignment(LayoutAlignment.RIGHT | LayoutAlignment.TOP);
        toastDialog.setContentCustomComponent(component1);
        toastDialog.setTransparent(true);
        toastDialog.setSize(250, 100);
        toastDialog.setOffset(30, 220);
        toastDialog.setDialogListener(new BaseDialog.DialogListener() {
            @Override
            public boolean isTouchOutside() {
                HiLog.info(LABEL, "isTouchOutside");
                destroyDialog(toastDialog);
                return false;
            }
        });
        toastDialog.show();

        getUITaskDispatcher().delayDispatch(new Runnable() {
            @Override
            public void run() {
                destroyDialog(toastDialog);
            }
        }, 2000);
    }

    private void destroyDialog(CommonDialog dialog) {
        if (dialog != null) {
            dialog.destroy();
        }
    }

    /**
     * layoutShow
     *
     * @param code code
     */
    public void layoutShow(int code) {
        switch (code) {
            case 0:
                ((FractionAbility) getAbility()).getFractionManager()
                    .startFractionScheduler()
                    .replace(ResourceTable.Id_main_stack, new XyChartFraction())
                    .submit();

                break;
            case 1:
                ((FractionAbility) getAbility()).getFractionManager()
                    .startFractionScheduler()
                    .replace(ResourceTable.Id_main_stack, new StyledXyChartFraction())
                    .submit();


                break;
            case 2:
                ((FractionAbility) getAbility()).getFractionManager()
                    .startFractionScheduler()
                    .replace(ResourceTable.Id_main_stack, new LineChartFraction())
                    .submit();

                break;
            case 3:
                ((FractionAbility) getAbility()).getFractionManager()
                    .startFractionScheduler()
                    .replace(ResourceTable.Id_main_stack, new StackedLineChartFraction())
                    .submit();

                break;
            case 4:
                ((FractionAbility) getAbility()).getFractionManager()
                    .startFractionScheduler()
                    .replace(ResourceTable.Id_main_stack, new BarChartFraction())
                    .submit();
                break;
            case 5:
                ((FractionAbility) getAbility()).getFractionManager()
                    .startFractionScheduler()
                    .replace(ResourceTable.Id_main_stack, new StackedBarChartFraction())
                    .submit();
                break;
            default:
                break;
        }
    }

    private void initVibrator() {
        vibratorAgent = new VibratorAgent();
        // 查询硬件设备上的振动器列表
        List<Integer> vibratorList = vibratorAgent.getVibratorIdList();
        if (vibratorList.isEmpty()) {
            vibratorAgent = null;
            return;
        }
        vibratorId = vibratorList.get(0);
    }

    private boolean hasVibrator() {
        // 查询指定的振动器是否支持指定的振动效果
        boolean isSupport = vibratorAgent.isEffectSupport(vibratorId,
            VibrationPattern.VIBRATOR_TYPE_CAMERA_CLICK);
        return isSupport;
    }

    private void startVibrator() {
        // 创建指定振动时长的一次性振动
        boolean b = vibratorAgent.startOnce(vibratorId, 1);
    }

    @Override
    public void onActive() {
        super.onActive();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }
}
